<script setup>
import { onMounted, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { listByConditionApi } from '@/api/publish'
import { getDescById } from '@/api/campusOrShop'
import { getConditionListApi, getBrandListApi } from '@/api/category'
import { onBeforeRouteUpdate } from 'vue-router'
const route = useRoute()

// 车辆列表
const vehicleInfoDtoList = ref([])
const setCarList = async () => {
  // 默认查第一页
  const res = await listByConditionApi({ ...queryParams.value, currentPage: 1 })
  vehicleInfoDtoList.value = res.data
}

// 筛选条件列表
const categories = ref({})
const setCategories = async (cid) => {
  const res = await getConditionListApi(cid || 0)
  categories.value = res.data
}

// 查询条件
const queryParams = ref({
  categoryId: route.query.categoryId ? parseInt(route.query.categoryId) : '', // 一级分类（车辆类型）
  nameMatch: route.query.nameMatch,
  brandIds: [],
  campusOrShopId: '',
  sortField: 1,
  minPrice: null,
  maxPrice: null,
  pageSize: 10
})

// 【您已选择】数组
const allSelected = ref({
  categoryId: '', // 一级分类（车辆类型）
  campusOrShopId: '',
  brandIds: [], // 二级分类（品牌、学校与店铺）
  priceRange: '',
  nameMatch: route.query.nameMatch ? '搜索：' + route.query.nameMatch : ''
})

// 您已选择：移除单选标签
const removeSelectedSingle = async (key) => {
  queryParams.value[key] = ''
  allSelected.value[key] = ''
  if (key === 'priceRange') {
    queryParams.value['minPrice'] = ''
    queryParams.value['maxPrice'] = ''
    allSelected.value['priceRange'] = ''
  }
  // 如果移除车辆类型则重加品牌列表
  if (key === 'categoryId') {
    const res = await getBrandListApi(0)
    categories.value.brandList = res.data
  }
}

// 您已选择：移除复选标签
const removeSelectedMulti = (id) => {
  queryParams.value.brandIds = queryParams.value.brandIds.filter(
    (e) => e !== id
  )
  allSelected.value.brandIds = allSelected.value.brandIds.filter(
    (e) => e.id !== id
  )
}

// 车辆类型单选框
const categoryIdChange = async (item) => {
  // 刷新品牌筛选列表
  const res = await getBrandListApi(item.id)
  categories.value.brandList = res.data

  // 清空之前选的品牌
  queryParams.value.brandIds = []
  allSelected.value.brandIds = []

  queryParams.value.categoryId = item.id
  allSelected.value.categoryId = item.name
}

// 学校单选框
const campusIdChange = (item) => {
  queryParams.value.campusOrShopId = item.id
  allSelected.value.campusOrShopId = item.name
}

// 价格单选框
const priceChange = (minPrice, maxPrice) => {
  queryParams.value.minPrice = minPrice
  queryParams.value.maxPrice = maxPrice

  allSelected.value.priceRange = transPrice(minPrice, maxPrice)
}
// 价格单位转换函数
const transPrice = (min, max) => {
  let minp = min === 0 ? 0 : Math.round(min / 10000)
  let maxp = Math.round(max / 10000) + '万'
  return `${minp}-${maxp}`
}
// 获取最小值输入框DOM
const minPriceInp = ref(null)
const maxPriceInp = ref(null)
// 确定按钮是否可用
const inputEnable = ref(false)
// 最大值input事件回调
const validateRule = () => {
  const minP = minPriceInp.value.value
  const maxP = maxPriceInp.value.value
  if (minP < 0 || maxP < 0) {
    inputEnable.value = false
  } else if (minP >= maxP) {
    inputEnable.value = false
  } else {
    inputEnable.value = true
  }
}
const comfirm = () => {
  if (inputEnable.value) {
    queryParams.value.minPrice = minPriceInp.value.value
    queryParams.value.maxPrice = maxPriceInp.value.value
  }
}

// 品牌和学校复选框
const subCategoryIdChange = (item) => {
  if (queryParams.value.brandIds.includes(item.id)) {
    queryParams.value.brandIds = queryParams.value.brandIds.filter(
      (e) => e !== item.id
    )
    allSelected.value.brandIds = allSelected.value.brandIds.filter(
      (e) => e.id !== item.id
    )
  } else {
    queryParams.value.brandIds.push(item.id)
    allSelected.value.brandIds.push(item)
  }
}

// 点进某个学校或店铺时查询数据并渲染
const showDesc = ref(false)
const categoryData = ref({})
// categoryData为学校或商店
const setCategoryData = async () => {
  const res = await getDescById(route.query.campusOrShopId)
  categoryData.value = res.data
}

// 滚动分页功能

const isBan = ref(false)
const currentPage = ref(1)
const load = async () => {
  currentPage.value++
  const res = await listByConditionApi({
    ...queryParams.value,
    currentPage: currentPage.value
  })
  if (res.data == null || res.data.length === 0) {
    isBan.value = true
  } else {
    vehicleInfoDtoList.value = [...vehicleInfoDtoList.value, ...res.data]
  }
}

// 查询参数变化时，重新获取数据
watch(
  queryParams,
  () => {
    // 当查询条件变化时，重置滚动分页参数
    currentPage.value = 1
    isBan.value = false
    setCarList()
  },
  { deep: true }
)

onMounted(async () => {
  await setCategories(route.query.categoryId)
  // 点进某个学校或店铺
  if (route.query.campusOrShopId) {
    setCategoryData()
    showDesc.value = true
    queryParams.value.campusOrShopId = route.query.campusOrShopId
  }
  // 点进某个品牌
  if (route.query.brandId) {
    queryParams.value.brandIds = [parseInt(route.query.brandId)]
    categories.value.brandList.forEach((e) => {
      if (e.id == route.query.brandId) allSelected.value.brandIds.push(e)
    })
  }
  // 如果有车辆分类则给其设置选中
  if (route.query.categoryId) {
    categories.value.vehicleList.forEach((e) => {
      if (e.id == route.query.categoryId) allSelected.value.categoryId = e.name
    })
  }
  setCarList()
})

onBeforeRouteUpdate((to) => {
  queryParams.value.nameMatch = to.query.nameMatch
  allSelected.value.nameMatch = '搜索：' + to.query.nameMatch
})
</script>

<template>
  <div class="container">
    <!-- 面包屑 -->
    <div class="bread-container">
      <el-breadcrumb separator=">">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item
          v-if="Object.keys(categoryData).length > 0"
          :to="{ path: `/campusOrShop/${categoryData.type}` }"
        >
          {{ categoryData.type === 1 ? '校园圈' : '全部店铺' }}
        </el-breadcrumb-item>
        <el-breadcrumb-item>{{
          categoryData.name || '条件选车'
        }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 条件筛选区域 -->
    <div class="head-container">
      <div class="desc" v-if="showDesc">
        <DescCard
          :count="categoryData.count"
          :todayNew="categoryData.todayCount"
          :campusName="categoryData.name"
          :picture="categoryData.picture"
          :addr="categoryData.addr"
        />
      </div>
      <div
        class="condition-filter"
        :class="{ move2right: route.query.campusOrShopId }"
      >
        <!-- 分类 -->
        <div>
          <span class="field">分&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;类:</span>
          <ul>
            <li
              v-for="item in categories.vehicleList"
              :key="item.id"
              @click.prevent="categoryIdChange(item)"
            >
              <el-check-tag
                size="small"
                :checked="item.id === queryParams.categoryId"
                type="warning"
              >
                {{ item.name }}
              </el-check-tag>
            </li>
          </ul>
        </div>
        <!-- 学校 -->
        <div v-if="!route.query.campusOrShopId">
          <span class="field">学&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;校:</span>
          <ul>
            <li
              v-for="item in categories.campusList"
              :key="item.id"
              @click.prevent="campusIdChange(item)"
            >
              <el-check-tag
                size="small"
                :checked="item.id == queryParams.campusOrShopId"
                type="warning"
              >
                {{ item.name }}
              </el-check-tag>
            </li>
          </ul>
        </div>
        <!-- 品牌 -->
        <div>
          <span class="field">品&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;牌:</span>
          <ul class="brand">
            <li
              v-for="item in categories.brandList"
              :key="item.id"
              @click.prevent="subCategoryIdChange(item)"
            >
              <el-check-tag
                size="small"
                :checked="queryParams.brandIds.includes(item.id)"
                type="success"
              >
                {{ item.name }}
              </el-check-tag>
            </li>
          </ul>
        </div>
        <!-- 价格 -->
        <div class="price">
          <span class="field">价&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;格:</span>
          <ul>
            <li
              :class="{
                current:
                  queryParams.maxPrice === 30000 && queryParams.minPrice === 0
              }"
              @click="priceChange(0, 30000)"
            >
              0-3万
            </li>
            <li
              :class="{
                current:
                  queryParams.maxPrice === 50000 &&
                  queryParams.minPrice === 30000
              }"
              @click="priceChange(30000, 50000)"
            >
              3-5万
            </li>
            <li
              :class="{
                current:
                  queryParams.maxPrice === 80000 &&
                  queryParams.minPrice === 50000
              }"
              @click="priceChange(50000, 80000)"
            >
              5-8万
            </li>
            <li
              :class="{
                current:
                  queryParams.maxPrice === 100000 &&
                  queryParams.minPrice === 80000
              }"
              @click="priceChange(80000, 100000)"
            >
              8-10万
            </li>
            <li
              :class="{
                current:
                  queryParams.maxPrice === 150000 &&
                  queryParams.minPrice === 100000
              }"
              @click="priceChange(100000, 150000)"
            >
              10-15万
            </li>
            <div class="price-range">
              <input ref="minPriceInp" type="text" @input="validateRule" />
              <span>-</span>
              <input ref="maxPriceInp" type="text" @input="validateRule" />
              <span>元</span>
              <a
                :class="{ active: inputEnable }"
                href="javascript:;;"
                @click.prevent="comfirm"
                >确定</a
              >
            </div>
          </ul>
        </div>
        <!-- 其他 -->
        <!-- <div>
          <span class="field">其&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;他:</span>
          <ul>
            <li>
              <el-check-tag
                style="background-color: #fff"
                :checked="false"
                type="primary"
              >
                车龄
              </el-check-tag>
            </li>
            <li>
              <el-check-tag
                style="background-color: #fff"
                :checked="false"
                type="primary"
              >
                里程
              </el-check-tag>
            </li>
            <li>
              <el-check-tag
                style="background-color: #fff"
                :checked="false"
                type="primary"
              >
                颜色
              </el-check-tag>
            </li>
          </ul>
        </div> -->
        <!-- 您已选择 -->
        <div class="selected">
          <span>您已选择&nbsp;:</span>
          <ul>
            <li
              v-show="key !== 'brandIds' && value !== ''"
              v-for="(value, key, index) in allSelected"
              :key="index"
            >
              <el-tag
                round
                effect="dark"
                closable
                :type="key === 'nameMatch' ? 'warning' : 'success'"
                @close="removeSelectedSingle(key)"
              >
                {{ value }}
              </el-tag>
            </li>
            <li v-for="i in allSelected.brandIds" :key="i.id">
              <el-tag
                round
                effect="dark"
                closable
                type="primary"
                @close="removeSelectedMulti(i.id)"
              >
                {{ i.name }}
              </el-tag>
            </li>
          </ul>
        </div>
      </div>
    </div>

    <!-- 商品区域 -->
    <div class="sub-container">
      <el-tabs v-model="queryParams.sortField">
        <el-tab-pane label="最新上架" name="1"></el-tab-pane>
        <el-tab-pane label="价格最低" name="2"></el-tab-pane>
      </el-tabs>
      <div
        v-if="vehicleInfoDtoList.length > 0"
        class="body"
        v-infinite-scroll="load"
        :infinite-scroll-disabled="isBan"
      >
        <!-- 商品列表-->
        <ul>
          <li v-for="car in vehicleInfoDtoList" :key="car.id">
            <car-item-publish :car="car" />
          </li>
        </ul>
      </div>
      <div class="empty" v-else>
        <el-empty
          class="emp-img"
          description="暂无更多"
          image="/src/assets/images/empty.png"
          :image-size="300"
        />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.head-container {
  margin: 10px 0;
  padding: 20px 10px 10px;
  background-color: #fff;
  display: flex;

  .condition-filter {
    flex: 1;
    overflow: hidden;
    padding-left: 8px;
    > div {
      display: flex;
      margin-bottom: 15px;

      > span {
        line-height: 28px;
        color: #666;
        margin-right: 20px;
      }

      ul {
        display: flex;
        flex-wrap: wrap;

        li {
          margin-right: 10px;
          line-height: 28px;
        }
      }

      .brand {
        li {
          width: 58px;
        }
      }
    }

    .price {
      height: 24px;
      span {
        line-height: 24px;
      }
      li {
        margin-right: 15px;
        line-height: 24px;
        padding: 0 5px;

        &.current {
          border: 1px solid #25ccf7;
          box-shadow: 0px 0px 2px 2px #9aecdb;
          border-radius: 5px;
        }
      }
      .price-range {
        display: flex;
        align-items: center;

        input {
          padding: 0 5px;
          width: 70px;
          height: 100%;
          border: 1px solid #ccc;
          border-radius: 2px;
        }

        span {
          margin: 0 3px;
          font-size: 16px;
          color: #666;
        }

        a {
          margin-left: 5px;
          padding: 2px 10px 2px 8px;
          background-color: #d0d0d0;
          color: #fff;
          border-radius: 4px;

          &.active {
            background-color: $xtxColor;
          }
        }
      }
    }
    .selected {
      margin-top: 10px;
      padding-top: 5px;
      border-top: 1px solid #eee;
      > span {
        width: 82px;
        margin-right: 13px;
      }
      ul {
        flex-wrap: wrap;
      }
    }

    &.move2right {
      // border-left: 6px double #9aecdb;
      border: 1px solid #25ccf7;
      box-shadow: 0px 0px 3px 3px #9aecdb;
      border-radius: 10px;
      padding: 20px 0 0 30px;
    }
  }
}
.sub-container {
  padding: 5px 0 0 25px;
  background-color: #fff;

  .body {
    ul {
      display: flex;
      flex-wrap: wrap;

      li {
        margin: 0 15px 25px 0;
      }
    }
  }
  .empty {
    position: relative;
    height: 500px;

    .emp-img {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
  }
}
</style>
